//
//  MessageViewController.m
//  ArtWalker
//
//  Created by Mac Jc on 15/8/3.
//  Copyright (c) 2015年 Mac Jc. All rights reserved.
//

#import "MessageViewController.h"
#import "TLSpringFlowLayout.h"
#import "MessageCollectionViewCell.h"
#import "InfoMationCollectionViewCell.h"
#import "MessageCollectionViewController.h"
#import "AllHeader.h"
#import "InfnMationCollectionViewController.h"
#import "MessageTalkViewController.h"
#import "ChatListViewController.h"
#import "SCHDStateViewController.h"
#import "STUDStateViewController.h"
#import "ChatViewController.h"

#import "FriendsCollectionViewCell.h"
#import "FriendsModel.h"

#define kMyFollowersURL @"http://arts1.cn/app/myfriend"

@interface MessageViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/**
 *  导航栏按钮
 */
@property (nonatomic ,strong) UISegmentedControl *messageSegmentControl;

/**
 *  消息页面
 */
@property (nonatomic ,strong) MessageCollectionViewController *messageVC;

@property (nonatomic ,strong) ChatListViewController *chatView;

/**
 *  资讯页面
 */
@property (nonatomic ,strong) InfnMationCollectionViewController *infoMationVC;

//记录上一次显示的视图
@property (nonatomic ,strong) UIViewController *lastVC;


@property (nonatomic,strong) UICollectionView *friendsCollectionView;
@property (nonatomic,strong) UIView *chatShadowView;
@property (nonatomic,strong) NSDictionary *friendsDic;
@property (nonatomic ,strong) NSMutableArray *friendArray;


@end

@implementation MessageViewController

- (NSMutableArray *)friendArray{
    if (_friendArray == nil)
    {
        self.friendArray = [NSMutableArray array];
    }
    return _friendArray;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = kBackgroundColor;
    //设置导航栏的阴影
    //    [self.navigationController.navigationBar dropShadowWithOffset:CGSizeMake(0, 1) radius:1 color:[UIColor blackColor] opacity:0.3];
    //设置导航栏的颜色
    self.navigationController.navigationBar.barTintColor = kCustomColor(255, 255, 255, 1.0);
    
    [self creactInfoMationCollectionView];
    [self navigationControllerVIew];
    [self requestFriendsData];
}



#pragma mark ------------------------------------------------------------------
#pragma mark - 创建好友列表
- (void)createFriendsCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
    _friendsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (SCREEN_WIDTH - 70)/6 + 10 + 15) collectionViewLayout:layout];
    _friendsCollectionView.backgroundColor = [UIColor whiteColor];
    _friendsCollectionView.delegate = self;
    _friendsCollectionView.dataSource = self;
    _friendsCollectionView.alwaysBounceHorizontal = YES;
    _friendsCollectionView.showsHorizontalScrollIndicator = NO;
    [_friendsCollectionView registerClass:[FriendsCollectionViewCell class] forCellWithReuseIdentifier:@"friendsCollectionCell"];
    
    _chatShadowView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, (SCREEN_WIDTH - 80)/7 + 10 + 15)];
    [UIView viewWideForShadowColor:_chatShadowView];
    [_chatShadowView addSubview:_friendsCollectionView];
    
    [self.view addSubview:_chatShadowView];
}

#pragma mark - 请求好友列表
- (void)requestFriendsData{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    NSString *key = dic[@"data"][@"key"];
    
    NSLog(@"消息页%@,%@",uid,key);
    NSDictionary *pardic = [NSDictionary dictionary];
    
    if (uid && key)
    {
        pardic = @{@"uid":uid,
                   @"key":key};
    }
    
    [manage POST:kMyFollowersURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             
             int status = [dic[@"status"] intValue];
             NSLog(@"status = %d",status);
             if (status == 1) {
                 
                 NSArray *list = dic[@"list"];
                 [self.friendArray removeAllObjects];
                 for (NSDictionary *dict in list)
                 {
                     FriendsModel *model = [[FriendsModel alloc] init];
                     [model setValuesForKeysWithDictionary:dict];
                     [self.friendArray addObject:model];
                 }
                 // 请求成功的时候调用这个block
                 NSLog(@"获取我的好友列表数据请求--%@", dic);
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}



#pragma mark ------------------------------------------------------------------
#pragma mark -- UICollectionViewDelegateFlowLayout

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.friendArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_WIDTH - 80)/7, (SCREEN_WIDTH - 80)/7 + 15);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FriendsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"friendsCollectionCell" forIndexPath:indexPath];
    FriendsModel *model = _friendArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    FriendsModel *model = _friendArray[indexPath.row];
    
    ChatViewController *conversationVC = [[ChatViewController alloc]init];
    //这个类型表示是私聊
    conversationVC.conversationType = ConversationType_PRIVATE;
//    conversationVC.targetId = @"1"; //这里模拟自己给自己发消息，您可以替换成其他登录的用户的UserId
    conversationVC.targetId = model.userId; //这里模拟自己给自己发消息，您可以替换成其他登录的用户的UserId
    conversationVC.userName = model.nickName;

    conversationVC.title = model.nickName;
    
//            RCUserInfo *user = [[RCUserInfo alloc]init];
//            user.userId = model.userId;
//            user.name = model.nickName;
//            user.portraitUri = model.userFace;
    
//            return completion(user);
    
    
    
    
    
    //  设置头像类型-圆形
    [conversationVC setMessageAvatarStyle:(RC_USER_AVATAR_CYCLE)];
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:conversationVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
    
}



#pragma mark ------------------------------------------------------------------
#pragma mark - 消息
- (void)creactChatListViewController{
    //初始化当前类，并设置需要显示的会话类型和聚合会话类型
    _chatView = [[ChatListViewController alloc] initWithDisplayConversationTypes:@[@(ConversationType_PRIVATE)] collectionConversationType:nil];
    [self addChildViewController:_chatView];
    _chatView.view.frame = CGRectMake(0, 64 + (SCREEN_WIDTH - 80)/7 + 10 + 15 + 9, SCREEN_WIDTH, SCREEN_HEIGHT - 113);
    _chatView.view.backgroundColor = kBackgroundColor;
    //设置头像为圆角边型
    [_chatView setConversationAvatarStyle:RC_USER_AVATAR_CYCLE];
    //设置头像大小
    [_chatView setConversationPortraitSize:CGSizeMake(40, 40)];
//    __block MessageViewController *messageView = self;
    //进入会话页面
    _chatView.pushChatListView = ^(NSIndexPath *indexPath)
    {
        
        FriendsModel *model = _friendArray[indexPath.row];
//        RCConversationViewController *conversationVC = [[RCConversationViewController alloc]init];
//        
//        //隐藏tabbar按钮
//        messageView.hidesBottomBarWhenPushed = YES;
//        conversationVC.view.backgroundColor = kBackgroundColor;
//        conversationVC.conversationType = ConversationType_PRIVATE;  //  会话类型
//        conversationVC.targetId = model.userId;  //  会话 Id
//        conversationVC.userName = model.nickName;  //  会话名称
//        conversationVC.title = model.nickName;  //  会话名称
//        [messageView.navigationController pushViewController:conversationVC animated:YES];
//        //返回页面重新显示tabbar按钮
//        messageView.hidesBottomBarWhenPushed = NO;
//        //刷新会话列表
//        [messageView.chatView refreshConversationTableViewIfNeeded];
        
        
        ChatViewController *conversationVC = [[ChatViewController alloc]init];
        //这个类型表示是私聊
        conversationVC.conversationType = ConversationType_PRIVATE;
        //    conversationVC.targetId = @"1"; //这里模拟自己给自己发消息，您可以替换成其他登录的用户的UserId
        conversationVC.targetId = model.userId; //这里模拟自己给自己发消息，您可以替换成其他登录的用户的UserId
        conversationVC.userName = model.nickName;
        
        conversationVC.title = model.nickName;
        
        //  设置头像类型-圆形
        [conversationVC setMessageAvatarStyle:(RC_USER_AVATAR_CYCLE)];
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:conversationVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    };
    [self.view addSubview:_chatView.view];
    
}

#pragma mark - 资讯
- (void)creactInfoMationCollectionView{
    //初始化UICollectionViewFlowLayout
    UICollectionViewFlowLayout *Layout = [[UICollectionViewFlowLayout alloc] init];
    _infoMationVC = [[InfnMationCollectionViewController alloc] initWithCollectionViewLayout:Layout];
    [self addChildViewController:_infoMationVC];
    
    self.infoMationVC.collectionView.alwaysBounceVertical = YES;
    //设置上下间距
    Layout.minimumInteritemSpacing = 0;
    //设置左右间距
    Layout.minimumLineSpacing = 8;
    Layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH - 16, 10);
    Layout.itemSize = CGSizeMake(SCREEN_WIDTH - 16, 70);
    [self.view addSubview:_infoMationVC.view];
    
    __weak MessageViewController *messAgeView = self;
    _infoMationVC.pushInfoView = ^(InfoMactionModel *model)
    {
        SCHDStateViewController *state = [[SCHDStateViewController alloc] init];
        state.ID = model.Id;
        [messAgeView.navigationController pushViewController:state animated:YES];
        messAgeView.hidesBottomBarWhenPushed = NO;
    };
    //设置大小
    _infoMationVC.view.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 79);
    _infoMationVC.navigationController.navigationBar.tintColor = kCustomColor(50, 50, 70, 1);
    
}

#pragma mark - 导航栏
- (void)navigationControllerVIew{
    //获取导航栏的标题
    NSArray *segmentArr = @[@"资讯",@"消息"];
    //加入到UISegmentControl
    _messageSegmentControl = [[UISegmentedControl alloc] initWithItems:segmentArr];
    //设置选中的颜色
    _messageSegmentControl.tintColor = [UIColor colorWithRed: 0.1569 green: 0.1569 blue: 0.1961 alpha: 1.0];
    //设置UISegmentControl的大小
    _messageSegmentControl.frame = CGRectMake(10, 5, SCREEN_WIDTH - 20, 30);
    //设置点击UISegmentControl的事件
    [_messageSegmentControl addTarget:self action:@selector(tapSegment:) forControlEvents:UIControlEventValueChanged];
    //默认选择的下标为第一个
    [_messageSegmentControl setSelectedSegmentIndex:0];
    
    self.navigationItem.titleView = _messageSegmentControl;
    [self creactInfoMationCollectionView];
    
    
    //设置用户信息提供者,页面展现的用户头像及昵称都会从此代理取
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    
}

#pragma mark - segmentController
- (void)tapSegment:(UISegmentedControl *)index{
    if(index.selectedSegmentIndex == 0)
    {
        [_chatView.view removeFromSuperview];
        [_chatShadowView removeFromSuperview];
        [_chatView removeFromParentViewController];
        //调用资讯页面
        [self creactInfoMationCollectionView];
    }
    else
    {
        [_infoMationVC.view removeFromSuperview];
        [_infoMationVC removeFromParentViewController];
        //调用消息页面
        [self creactChatListViewController];
        [self createFriendsCollectionView];
    }
}




/**
 *此方法中要提供给融云用户的信息，建议缓存到本地，然后改方法每次从您的缓存返回
 */
//- (void)getUserInfoWithUserId:(NSString *)userId completion:(void(^)(RCUserInfo* userInfo))completion{
    //此处为了演示写了一个用户信息
//    if ([@"1" isEqual:userId]) {
//        RCUserInfo *user = [[RCUserInfo alloc]init];
//        user.userId = @"1";
//        user.name = @"测试1";
//        user.portraitUri = @"https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1756054607,4047938258&fm=96&s=94D712D20AA1875519EB37BE0300C008";
//        
//        return completion(user);
//    }
//}



@end
